from __future__ import absolute_import
import os, errno
import logging
logger = logging.getLogger('pkgr.util')

import os
def touch(fname):
    if os.path.exists(fname):
        os.utime(fname, None)
    else:
        open(fname, 'w').close()
        
        
'''
foo-1.1-1.fc17:0.noarch - name version release epoch arch
foo-1.1:0.noarch - name ver epoch arch
foo:0 - name epoch arch
foo.noarch - name arch
foo - name
'''
import re
repkg = re.compile('''
    ([\w\d\_]+)
    (?:-([\w\d\.]+))?
    (?:-([\.\w\d]+))?
    (?::([\d]+))?
    (?:\.([\w\d]+))?
''', re.X)
def parse_package_name(name):
    name, version, release, epoch, arch = repkg.match(name).groups()
    return (name, version, release, epoch, arch)
    
def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc: # Python >2.5
        if exc.errno == errno.EEXIST:
            pass
        else: raise
        
import bz2
def decompress_chunked(source, dest, ztype):

    #if ztype not in _available_compression:
    #    msg = "%s compression not available" % ztype
    #    raise Errors.MiscError, msg
    
    if ztype == 'bz2':
        s_fn = bz2.BZ2File(source, 'r')
    #elif ztype == 'xz':            
    #    s_fn = lzma.LZMAFile(source, 'r')
    #elif ztype == 'gz':
    #    s_fn = gzip.GzipFile(source, 'r')
    
    destination = open(dest, 'w')
    read = 0
    while True:
        try:
            data = s_fn.read(1024000)
        except IOError:
            break
        if not data: break
        read += len(data)
        try:
            destination.write(data)
        except (OSError, IOError), e:
            #msg = "Error writing to file %s: %s" % (dest, str(e))
            #raise Errors.MiscError, msg
            raise
            
    logger.debug('Decompressed %s bytes', read)
    
    destination.close()
    s_fn.close()
    
    

    
